import React, { useState } from 'react';
import { Divider, Button, message as Message } from 'antd';
import { LinkOutlined } from '@ant-design/icons';
import type { GetProp } from 'antd';
import { Bubble, Sender } from '@ant-design/x';
import { ConditionBar } from './ConditionBar';
import { useRef } from 'react';
import { Clock } from 'lucide-react';
import {
  createInterview,
  getNewSessionId,
  reviewChat,
} from '@/apis/hireSphere';
import { LOGO } from '@/state/common';
import './index.scss';

interface ChatHistory {
  key: string;
  role: 'assistant' | 'user';
  content: string;
  loading?: boolean;
}

const UnInterview = () => {
  return (
    <div className="my-3 mr-3 flex flex-1 flex-col items-center justify-center rounded-br-2xl rounded-tr-2xl bg-[#F9FAFB]">
      <div className="logo">
        <img className="h-24" src={LOGO} alt="logo" />
      </div>
      <div className="mt-5 text-3xl font-bold">欢迎使用Hire Sphere</div>
      <div className="mt-6 text-lg text-gray-500">
        请填写好模拟面试信息，以便我们更好地为您提供服务
      </div>
    </div>
  );
};

const Hiresphere: React.FC = () => {
  const listRef = useRef(null);
  const [sessionId, setSessionId] = useState<number>();
  const [isInterviewing, setIsInterviewing] = useState(false);
  const [message, setMessage] = useState<string>();
  const [chatHistory, setChatHistory] = useState<ChatHistory[]>([]);

  const rolesOpt: GetProp<typeof Bubble.List, 'roles'> = {
    ai: {
      placement: 'start',
      typing: { step: 5, interval: 120 },
      style: {
        maxWidth: 600,
      },
      styles: {
        content: {
          backgroundColor: '#E5E7EB',
        },
      },
    },
    user: {
      placement: 'end',
      styles: {
        content: {
          backgroundColor: '#4F46E5',
          color: '#fff',
        },
      },
    },
  };

  const handleSend = async (message: string) => {
    if (!message) return;
    // 添加用户消息
    const userMessage: ChatHistory = {
      key: String(chatHistory.length + 1),
      role: 'user',
      content: message,
    };

    // 添加 AI 的 loading 占位
    const aiLoadingMessage: ChatHistory = {
      key: String(chatHistory.length + 2),
      role: 'assistant',
      content: '',
      loading: true,
    };
    setChatHistory((prev) => [...prev, userMessage, aiLoadingMessage]);
    setMessage('');

    const aiResponse = await reviewChat({
      answer: message,
      session_id: sessionId as number,
    });
    setChatHistory((prev) => {
      const newChatHistory = [...prev];
      const loadingIndex = newChatHistory.findIndex((item) => item.loading);
      if (loadingIndex !== -1) {
        newChatHistory[loadingIndex] = aiResponse; // 替换 loading 占位
      }
      return newChatHistory;
    });
  };

  const handleCreateInterview = async (data: {
    hc: string;
    pdf_url: string;
    question_num?: number;
    level?: number;
  }) => {
    setIsInterviewing(true);
    // 添加 AI 的 loading消息 占位
    const aiLoadingMessage: ChatHistory = {
      key: String(chatHistory.length + 2),
      role: 'assistant',
      content: '',
      loading: true,
    };
    setChatHistory((prev) => [...prev, aiLoadingMessage]);
    try {
      const { code, data: sessionResponse } = await getNewSessionId();
      setSessionId(sessionResponse.session_id);
      if (code !== 200) {
        Message.error('获取session_id失败');
        return;
      }
      const aiResponse = await createInterview({
        ...data,
        session_id: sessionResponse.session_id,
      });
      setChatHistory((prev) => {
        const newChatHistory = [...prev];
        const loadingIndex = newChatHistory.findIndex((item) => item.loading);
        if (loadingIndex !== -1) {
          newChatHistory[loadingIndex] = aiResponse; // 替换 loading 占位
        }
        return newChatHistory;
      });
    } catch (error) {
      Message.error('创建面试失败');
      setIsInterviewing(false);
    }
  };

  return (
    <div className="flex h-full w-full">
      <div className="my-3 ml-3 w-[350px] rounded-bl-2xl rounded-tl-2xl">
        <ConditionBar
          isInterviewing={isInterviewing}
          handleCreateInterview={handleCreateInterview}
        />
      </div>
      {isInterviewing ? (
        <div className="my-3 mr-3 flex flex-1 flex-col rounded-br-2xl rounded-tr-2xl bg-[#F9FAFB]">
          <header className="flex h-16 items-center justify-between border-b-[1px] px-4">
            <div className="header-left active relative ml-5">面试进行中</div>
            <div className="right flex items-center">
              <Clock size={18} />
              <div className="time ml-1 text-lg">45:32</div>
              <Divider type="vertical" />
              <div className="text-gray-600">已完成</div>
              <span className="ml-2 text-lg font-bold">8/12</span>
            </div>
          </header>
          <main className="flex-1 overflow-y-auto">
            <Bubble.List
              ref={listRef}
              roles={rolesOpt}
              style={{ height: '100%', padding: 16 }}
              items={chatHistory}
            />
          </main>
          <footer className="flex h-24 items-center justify-center border-t-[1px] px-4">
            <Sender
              allowSpeech
              prefix={<Button type="text" icon={<LinkOutlined />} />}
              value={message}
              onChange={(v) => {
                setMessage(v);
              }}
              onSubmit={handleSend}
            />
          </footer>
        </div>
      ) : (
        UnInterview()
      )}
    </div>
  );
};

export default Hiresphere;
